import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import createSagaMiddleware from 'redux-saga';

import modules from './modules';

import preloadedState from './preloadedState';
import {safe} from './safe';

const { rootSaga, rootReducer } = modules;

export default function configureStore() {
    const effectMiddleware = next => effect => {
        if (effect.type === 'FORK') {
            effect.payload.args[1] = safe(effect.payload.args[1]);
        }
        return next(effect);
    };

    const sagaMiddleware = createSagaMiddleware({
        effectMiddlewares: [effectMiddleware]
    });

    // const sagaMiddleware = createSagaMiddleware();
    const middlewares = [sagaMiddleware];
    const middlewareEnhancer = applyMiddleware(...middlewares);
    const store = createStore(rootReducer, preloadedState, composeWithDevTools((middlewareEnhancer)));
    sagaMiddleware.run(rootSaga);

    // var process = {
    //     env: {
    //         NODE_ENV: 'production'
    //     }
    // };
   
    if (process.env.NODE_ENV !== 'production' && module.hot) {
        module.hot.accept('./modules', () => store.replaceReducer(rootReducer))
    }
    
    return store;
}